package com.sxbbc.plat.controller.jz;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.function.common.GetRest;
import com.function.common.RestResponse;
import com.sxbbc.common.basics.exceptions.ThrowJsonException;
import com.sxbbc.common.basics.files.RestUploadFileInfo;
import com.sxbbc.common.basics.files.UploadUtils;
import com.sxbbc.common.basics.utils.calculation.CalcuUtils;
import com.sxbbc.common.basics.utils.statics.StaticUtils;
import com.sxbbc.common.core.entity.jz.*;
import com.sxbbc.common.core.enums.*;
import com.sxbbc.common.core.service.*;
import com.sxbbc.common.core.utils.BasePage;
import com.sxbbc.common.core.utils.FileUtils;
import com.sxbbc.common.core.utils.MultipartFileToFile;
import com.sxbbc.plat.common.MappingUtils;
import com.sxbbc.plat.util.SystemLog;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 图标/banner图/应用图设置 控制层
 *
 * @author leehao
 * @date 2019-05-14 10:13
 */
@Controller
public class IconController {

    @Autowired
    private IAppIconService appIconService;
    @Autowired
    private IAppBannerService appBannerService;
    @Autowired
    private IAppClassificationService appClassificationService;
    @Autowired
    private ProcClassifyMainService procClassifyMainService;
    @Autowired
    private ISiteKeyService siteKeyService;
    @Autowired
    private BBusinessService bBusinessService;

    /**
     * 图标列表页
     *
     * @param page 分页
     * @param icon 查询
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.SHOW_ICON_LIST)
    public ModelAndView showIconList(BasePage<AppIcon> page, AppIcon icon) {
        Page<AppIcon> pageInfo = appIconService.queryAppIconList(page, icon);
        // icon的list
        List<IconEnums> iconList = IconEnums.queryListByType(StaticUtils.ICON_TYPE_ICON);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_ICON_LIST);
        view.addObject("pageInfo", pageInfo);
        view.addObject("icon", icon);
        view.addObject("iconList", iconList);
        return view;
    }

    @RequestMapping(value = MappingUtils.SHOW_EDIT_ICON)
    public ModelAndView showEditIcon(Integer id) {
        AppIcon icon = appIconService.getById(id);
        // 事件
        List<EventEnums> allList = EventEnums.queryAllList();
        // icon的list
        List<IconEnums> iconList = IconEnums.queryListByType(StaticUtils.ICON_TYPE_ICON);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_EDIT_ICON);
        view.addObject("icon", icon);
        view.addObject("allList", allList);
        view.addObject("iconList", iconList);
        return view;
    }

    /**
     * 新增/编辑图标
     *
     * @param img  图标图片
     * @param icon 对象
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.EDIT_ICON)
    @ResponseBody
    @SystemLog(methods = "编辑app图标", module = "应用管理")
    public RestResponse editIcon(@RequestParam(required = false, value = "imgUrl") MultipartFile img,
                                 AppIcon icon) {
        if (StringUtils.isBlank(icon.getName())) {
            return GetRest.getFail("请输入图标名称");
        }
        if (icon.getDisplay() == null) {
            return GetRest.getFail("请选择是否在首页显示");
        }
        if (icon.getId() == null && img == null) {
            return GetRest.getFail("请上传图标图片");
        }
        if (StringUtils.isBlank(icon.getEvent())) {
            return GetRest.getFail("请选择事件类型");
        }
        if (StringUtils.equals(icon.getEvent(), EventEnums.OWN_BUSINESS.getUrl())) {
            QueryWrapper<BBusiness> wrapper = new QueryWrapper<>();
            wrapper.eq("b_type", BusinessTypeEnums.OWN_BUSINESS.getId()).eq("status", StaticUtils.STATUS_SUCCESS);
            BBusiness bBusiness = bBusinessService.getOne(wrapper);
            if (bBusiness == null) {
                return GetRest.getFail("当前还没有自营店铺");
            }
            icon.setUrl(String.valueOf(bBusiness.getId()));
        }
        // 图片上传
//        RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(img);
//        if (result.isStatus()) {
//            icon.setIcon(result.getData());
//        } else if (!result.isStatus() && img != null) {
//            return GetRest.getFail("图片上传失败");
//        }
        try {
            File fe= MultipartFileToFile.multipartFileToFile(img);
            String url = FileUtils.up(fe);
            icon.setIcon(url);
        }catch (Exception e){
            return GetRest.getFail("图片上传失败，请重试");
        }
        boolean save = appIconService.saveOrUpdate(icon);
        if (!save) {
            throw new ThrowJsonException("app图标保存失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 启用/隐藏图标
     *
     * @param icon id、show
     * @return boolean
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.HANDLE_ICON_DISPLAY)
    @ResponseBody
    @SystemLog(methods = "启用/隐藏app图标", module = "应用管理")
    public boolean handleIconDisplay(AppIcon icon) {
        return appIconService.updateById(icon);
    }

    /**
     * 删除图标
     *
     * @param id 图标id
     * @return boolean
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.DELETE_ICON)
    @ResponseBody
    @SystemLog(methods = "删除app图标", module = "应用管理")
    public boolean deleteIcon(Integer id) {
        return appIconService.removeById(id);
    }

    @RequestMapping(value = MappingUtils.SHOW_BANNER_LIST)
    public ModelAndView showBannerList(BasePage<AppBanner> page, AppBanner banner) {
        Page<AppBanner> pageInfo = appBannerService.queryAppIconList(page, banner);
        // banner的list
        List<IconEnums> iconList = IconEnums.queryListByType(StaticUtils.ICON_TYPE_BANNER);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_BANNER_LIST);
        view.addObject("pageInfo", pageInfo);
        view.addObject("iconList", iconList);
        view.addObject("banner", banner);
        return view;
    }

    @RequestMapping(value = MappingUtils.SHOW_EDIT_BANNER)
    public ModelAndView showEditBanner(Integer id) {
        AppBanner banner = appBannerService.getById(id);
        // 事件
        List<EventEnums> allList = EventEnums.queryAllList();
        // banner的list
        List<IconEnums> iconList = IconEnums.queryListByType(StaticUtils.ICON_TYPE_BANNER);
        List<BannerPositionEnums> positionList = BannerPositionEnums.queryShowList();
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_EDIT_BANNER);
        view.addObject("banner", banner);
        view.addObject("allList", allList);
        view.addObject("iconList", iconList);
        view.addObject("positionList", positionList);
        return view;
    }

    @RequestMapping(value = MappingUtils.EDIT_BANNER)
    @ResponseBody
    @SystemLog(methods = "新增/编辑banner图", module = "应用设置")
    public RestResponse editBanner(@RequestParam(required = false) MultipartFile img,
                                   AppBanner banner) {
        if (banner.getType() == null) {
            return GetRest.getFail("请选择banner图显示位置");
        }
        if (banner.getPosition() == null) {
            return GetRest.getFail("请选择banner图位置");
        }
        if (banner.getId() == null && img == null) {
            return GetRest.getFail("请上传图片");
        }
        if (StringUtils.isBlank(banner.getEvent())) {
            return GetRest.getFail("请选择事件类型");
        }
        if (StringUtils.equals(banner.getEvent(), EventEnums.OWN_BUSINESS.getUrl())) {
            QueryWrapper<BBusiness> wrapper = new QueryWrapper<>();
            wrapper.eq("b_type", BusinessTypeEnums.OWN_BUSINESS.getId()).eq("status", StaticUtils.STATUS_SUCCESS);
            BBusiness bBusiness = bBusinessService.getOne(wrapper);
            if (bBusiness == null) {
                return GetRest.getFail("当前还没有自营店铺");
            }
            banner.setUrl(String.valueOf(bBusiness.getId()));
        }
//        RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(img);
//        if (result.isStatus()) {
//            banner.setIcon(result.getData());
//        } else if (!result.isStatus() && img != null) {
//            return GetRest.getFail("图片上传失败");
//        }
        try {
            File fe= MultipartFileToFile.multipartFileToFile(img);
            String url = FileUtils.up(fe);
            banner.setIcon(url);
        }catch (Exception e){
            return GetRest.getFail("图片上传失败，请重试");
        }
        boolean save = appBannerService.saveOrUpdate(banner);
        if (!save) {
            throw new ThrowJsonException("banner图保存失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    @RequestMapping(value = MappingUtils.DELETE_BANNER)
    @ResponseBody
    @SystemLog(methods = "删除banner图", module = "应用设置")
    public boolean deleteBannerById(Integer id) {
        return appBannerService.removeById(id);
    }

    @RequestMapping(value = MappingUtils.SHOW_ADVERT_LIST)
    public ModelAndView showAdvertList() {
        List<IconEnums> advert = IconEnums.queryListByType(StaticUtils.ICON_TYPE_ADVERT);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_ADVERT_LIST);
        view.addObject("advert", advert);
        return view;
    }

    @RequestMapping(value = MappingUtils.SHOW_CLASSIFICATION_ICON_LIST)
    public ModelAndView showClassificationIconList(BasePage<AppClassification> page,
                                                   AppClassification classification) {
        //列表
        IPage<AppClassification> pageInfo = appClassificationService.queryClassificationList(page, classification);
        //跳转分类事件
        EventEnums classify = EventEnums.CLASSIFICATION;
        //跳转全部分类事件
        EventEnums classifyAll = EventEnums.CLASSIFICATION_ALL;
        //应用位置
        List<IconEnums> iconList = IconEnums.queryListByType(StaticUtils.ICON_TYPE_CLASSIFICATION);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_CLASSIFICATION_ICON_LIST);
        view.addObject("pageInfo", pageInfo);
        view.addObject("classify", classify);
        view.addObject("classifyAll", classifyAll);
        view.addObject("iconList", iconList);
        view.addObject("classify", classification);
        return view;
    }

    @RequestMapping(value = MappingUtils.SHOW_EDIT_CLASSIFICATION)
    public ModelAndView showEditClassification(Integer id) {
        AppClassification classification = appClassificationService.getById(id);
        //应用位置
        List<IconEnums> iconList = IconEnums.queryListByType(StaticUtils.ICON_TYPE_CLASSIFICATION);

        //跳转分类事件
        EventEnums classify = EventEnums.CLASSIFICATION;
        //跳转全部分类事件
        EventEnums classifyAll = EventEnums.CLASSIFICATION_ALL;
        //状态可用的一级分类
        ProcThirdClassifyMain thirdClassifyMain = new ProcThirdClassifyMain();
        thirdClassifyMain.setLevel(StaticUtils.FIRST_CLASSIFY);
        List<?> firstList = procClassifyMainService.queryClassifyListByPlat(thirdClassifyMain);
        List<?> secondList = new ArrayList<>();
        List<?> thirdList = new ArrayList<>();
        if (classification != null && StringUtils.equals(classification.getEvent(), EventEnums.CLASSIFICATION.getUrl())) {
            String[] classList = classification.getUrl().split(",");
            classification.setFirstClass(Integer.parseInt(classList[0]));
            classification.setSecondClass(Integer.parseInt(classList[1]));
            if (classList.length == 3) {
                classification.setThirdClass(Integer.parseInt(classList[2]));
            }
            secondList = procClassifyMainService.queryClassifyListAjax
                    (Integer.parseInt(classList[0]), ClassifyTypeEnums.PLAT_FORM.getId(),
                            null, StaticUtils.SECOND_CLASSIFY);
            thirdList = procClassifyMainService.queryClassifyListAjax
                    (Integer.parseInt(classList[1]), ClassifyTypeEnums.PLAT_FORM.getId(),
                            null, StaticUtils.THIRD_CLASSIFY);
        }
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_EDIT_CLASSIFICATION);
        view.addObject("classification", classification);
        view.addObject("firstList", firstList);
        view.addObject("secondList", secondList);
        view.addObject("thirdList", thirdList);
        view.addObject("classify", classify);
        view.addObject("classifyAll", classifyAll);
        view.addObject("iconList", iconList);
        return view;
    }

    @RequestMapping(value = MappingUtils.EDIT_CLASSIFICATION)
    @ResponseBody
    @SystemLog(methods = "新增/编辑分类图标", module = "应用管理")
    public RestResponse editClassification(MultipartFile imgUrl,
                                           AppClassification classification) {
        if (StringUtils.isBlank(classification.getName())) {
            return GetRest.getFail("请输入分类别名");
        }
        if (classification.getPosition() == null) {
            return GetRest.getFail("请选择图标位置");
        }
        if (CalcuUtils.getInstance().isEquals(classification.getPosition(), StaticUtils.ICON_POSITION_APP)) {
            if (classification.getName().length() > 4) {
                return GetRest.getFail("请不要输入超过4个汉字");
            }
        }
        if (StringUtils.isBlank(classification.getEvent())) {
            return GetRest.getFail("请选择事件类型");
        }
        if (StringUtils.equals(classification.getEvent(), EventEnums.CLASSIFICATION.getUrl())) {
            if (classification.getFirstClass() == null) {
                return GetRest.getFail("请选择一级分类");
            }
            if (classification.getSecondClass() == null) {
                return GetRest.getFail("请选择二级分类");
            }
            String url = null;
            if (classification.getThirdClass() == null) {
                url = classification.getFirstClass() + "," +
                        classification.getSecondClass();
                classification.setUrl(url);
                //return GetRest.getFail("请选择三级分类");
            } else {
                url = classification.getFirstClass() + "," +
                        classification.getSecondClass() + "," + classification.getThirdClass();
                classification.setUrl(url);
            }

        }
        if (classification.getId() == null && imgUrl == null) {
            return GetRest.getFail("请上传分类图标图片");
        }
        /*RestUploadFileInfo result = UploadUtils.getInstance().uploadFileQN(imgUrl);
        if (result.isStatus()) {
            classification.setIcon(result.getData());
        } else if (!result.isStatus() && imgUrl != null) {
            return GetRest.getFail("图片上传失败");
        }*/
        try {
            File fe= MultipartFileToFile.multipartFileToFile(imgUrl);
            String url = FileUtils.up(fe);
            classification.setIcon(url);
        }catch (Exception e){
            return GetRest.getFail("图片上传失败，请重试");
        }

        boolean save = appClassificationService.saveOrUpdate(classification);
        if (!save) {
            throw new ThrowJsonException("保存分类图标失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    @RequestMapping(value = MappingUtils.HANDLE_CLASSIFICATION_STATUS)
    @ResponseBody
    public boolean handleClassificationStatus(AppClassification c) {
        return appClassificationService.updateById(c);
    }

    @RequestMapping(value = MappingUtils.DELETE_CLASSIFICATION)
    @ResponseBody
    public boolean deleteClassification(Integer id) {
        return appClassificationService.removeById(id);
    }

    /* 首页关键词 */

    /**
     * 关键词列表
     *
     * @param page 分页
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.SHOW_SITE_KEY_LIST)
    public ModelAndView showSiteKeyList(BasePage<SiteKey> page) {
        IPage<SiteKey> pageInfo = siteKeyService.page(page);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_SITE_KEY_LIST);
        view.addObject("pageInfo", pageInfo);
        return view;
    }

    /**
     * 编辑关键词页面
     *
     * @param id 记录id
     * @return org.springframework.web.servlet.ModelAndView
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.SHOW_SITE_KEY_EDIT)
    public ModelAndView showSiteKeyEdit(Integer id) {
        SiteKey siteKey = siteKeyService.getById(id);
        ModelAndView view = new ModelAndView(MappingUtils.SHOW_SITE_KEY_EDIT);
        view.addObject("siteKey", siteKey);
        return view;
    }

    /**
     * 新增编辑关键词
     *
     * @param siteKey 。
     * @return com.function.common.RestResponse
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.EDIT_SITE_KEY)
    @ResponseBody
    @SystemLog(methods = "新增编辑关键词", module = "应用管理")
    public RestResponse editSiteKey(SiteKey siteKey) {
        if (StringUtils.isBlank(siteKey.getKeyVal())) {
            return GetRest.getFail("请输入关键词");
        }
        boolean save = siteKeyService.saveOrUpdate(siteKey);
        if (!save) {
            throw new ThrowJsonException("保存关键词失败");
        }
        return GetRest.getSuccess("保存成功");
    }

    /**
     * 删除关键词
     *
     * @param id 关键id
     * @return boolean
     * @author leehao
     */
    @RequestMapping(value = MappingUtils.DELETE_SITE_KEY)
    @ResponseBody
    @SystemLog(methods = "删除关键词", module = "应用管理")
    public boolean deleteSiteKey(Integer id) {
        return siteKeyService.removeById(id);
    }
}
